﻿using SW.EF.BLL.PermissionModule;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Autofac;
using SW.EF.DAL;
using SW.EF.Core;
using SW.EF.Core.Global;
using SW.EF.Web.FrameWork.Extension;
using SW.EF.Web.FrameWork.Infrastructures;
using SW.EF.Web.FrameWork.ValidationRule.PermissionModule;
using SW.EF.Web.FrameWork.ViewModel.PermissionModule;

namespace SW.EF.Web.Controllers
{
    public class HomeController : Controller
    {
        private readonly IUserService _userService;

        public HomeController()
        {
            this._userService = Engine.AopProvider.CreateInstance<IUserService>();
                //Engine.IocProvider.Resolve<IUserService>();
        }

        public ActionResult Login()
        {
            return View();
        }

        [Authorize]
        public ActionResult Index()
        {
            ViewBag.Account = User.Identity.Name;
            return View();
        }


        /// <summary>
        /// 首页左侧功能模块类目
        /// </summary>
        [Authorize]
        public ActionResult ModuleCategory()
        {
            var user = this._userService.GetUser(User.Identity.Name);
            if (user == null)
                return Json(ResponseJsonHelper.JsonState(false, "账号不存在，请联系管理员!"), JsonRequestBehavior.AllowGet);
            var listPermission = new List<Permission>();
            if (user.Roles.Any(x => x.RoleCode == EnumRoleCode.SuperAdmin.ToString()))
            {
                // 取出所有权限。
                listPermission = this._userService.GetModuleCategoryList(true, user.Id, null);
            }
            else
            {
                // 取出用户对应的权限
                // 取出角色对应的权限
            }
            return View(ConvertToModuleCategoryVmList(listPermission));
        }

        [HttpPost]
        [ActionName("Login")]
        public JsonResult LoginSubmit(AccountVm vm)
        {
            var result = new AccountVmValidationRule().Validate(vm);
            if (!result.IsValid)
                return Json(ResponseJsonHelper.JsonState(false, result.Errors.ToMessage()), JsonRequestBehavior.AllowGet);
            
            if (!this._userService.IsExistUser(vm.Account, Encrypt.Md5(vm.Password)))
                return Json(ResponseJsonHelper.JsonState(false, "请仔细检查，账号或密码错误!"), JsonRequestBehavior.AllowGet);
 
            var ticket = new FormsAuthenticationTicket(1, vm.Account, DateTime.Now, DateTime.Now.AddDays(7), false, "",
                "/");
            var cookieVal = FormsAuthentication.Encrypt(ticket);
            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieVal)
            {
                Expires = DateTime.Now.AddDays(7)
            };
            HttpContext.Response.Cookies.Add(cookie);
            return Json(ResponseJsonHelper.JsonState(true, "/Home/Index"), JsonRequestBehavior.AllowGet);
        }

        private static List<ModuleCategoryVm> ConvertToModuleCategoryVmList(List<Permission> permissions)
        {
            return permissions.Where(x => x.Deep == 1)
                .Select(module => new ModuleCategoryVm()
                {
                    Icon = module.Icon,
                    Name = module.PermissionName,
                    Id = module.Id,
                    Childs = permissions.Where(x => x.Deep == 2 && x.ParentId == module.Id)
                        .Select(field => new ModuleCategoryVm()
                        {
                            Id = field.Id,
                            Icon = field.Icon,
                            Name = field.PermissionName,
                            Url = field.Url
                        }).ToList()
                }).ToList();
        }
    }
}
